import React, { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Row, Col } from 'antd';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';
import { hotApi } from '../../services/hotApi';
import { useAsync } from '../../hooks';
import CustomCard from '../custom/CustomCard';
import CustomButton from '../custom/CustomButton';
import CustomSelect from '../custom/CustomSelect';
import CustomTag from '../custom/CustomTag';
import CustomSpin from '../custom/CustomSpin';
import CustomAlert from '../custom/CustomAlert';
import AnimatedList from '../ui/AnimatedList';
import CustomPieChart from '../charts/CustomPieChart';
import CustomColumnChart from '../charts/CustomColumnChart';
import CustomWordCloud from '../charts/CustomWordCloud';
import '../custom/customStyles.css';

interface HotItem {
  index: number;
  title: string;
  url: string;
  hot?: string | number;
  desc?: string;
  pic?: string;
  timestamp?: string;
}

interface HotData {
  platform: string;
  subtitle: string;
  update_time: string;
  data: HotItem[];
}

interface Platform {
  name: string;
  platform_name: string;
  type: string;
  description: string;
  available: boolean;
}

const HotDataPage: React.FC = () => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [selectedPlatform, setSelectedPlatform] = useState<string>('zhihu');
  const [hotData, setHotData] = useState<Record<string, HotData>>({});
  const [isLoading, setIsLoading] = useState<boolean>(false);
  
  const {
    data: platforms,
    loading: platformsLoading,
    error: platformsError,
    execute: fetchPlatforms
  } = useAsync(hotApi.getPlatforms, true);

  const {
    loading: dataLoading,
    error: dataError,
    execute: fetchData
  } = useAsync(hotApi.getPlatformData);

  const {
    loading: refreshLoading,
    error: refreshError,
    execute: refreshData
  } = useAsync(hotApi.refreshPlatformCache);

  // 获取平台数据
  const loadPlatformData = useCallback(async (platform: string) => {
    if (!platform) return;
    
    setIsLoading(true);
    try {
      const data = await fetchData(platform, 30);
      setHotData(prev => ({ ...prev, [platform]: data }));
    } catch (error) {
      console.error('获取热点数据失败:', error);
    } finally {
      setIsLoading(false);
    }
  }, [fetchData]);

  // 初始化加载
  useEffect(() => {
    if (selectedPlatform && !hotData[selectedPlatform]) {
      loadPlatformData(selectedPlatform);
    }
  }, [selectedPlatform, hotData, loadPlatformData]);

  const handleRefresh = async () => {
    try {
      await refreshData(selectedPlatform);
      // 刷新后重新获取数据
      await loadPlatformData(selectedPlatform);
    } catch (error) {
      console.error('刷新数据失败:', error);
    }
  };

  const handlePlatformChange = (platform: string) => {
    setSelectedPlatform(platform);
  };

  // 将热点数据转换为 AnimatedList 项目
  const convertToAnimatedListItems = (data: HotItem[]) => {
    return data.map((item, index) => ({
      id: item.index || index + 1,
      content: (
        <motion.div 
          className="hot-item-container"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: index * 0.05 }}
          whileHover={{ 
            scale: 1.02,
            transition: { duration: 0.2 }
          }}
        >
          <div 
            className="hot-item-index"
            style={{ 
              backgroundColor: index < 3 ? '#ff4d4f' : theme.glowColor,
              color: 'white',
              boxShadow: `0 4px 8px ${index < 3 ? 'rgba(255, 77, 79, 0.3)' : theme.glowColor + '40'}`
            }}
          >
            {item.index || index + 1}
          </div>
          
          <div className="hot-item-content">
            <div className="hot-item-title-row">
              <motion.a 
                href={item.url} 
                target="_blank" 
                rel="noopener noreferrer"
                className="hot-item-title-link"
                style={{ 
                  color: theme.glowColor,
                }}
                whileHover={{ 
                  color: mode === 'dark' ? '#fff' : '#000',
                  textShadow: `0 0 8px ${theme.glowColor}`
                }}
                transition={{ duration: 0.2 }}
              >
                {item.title}
              </motion.a>
              {item.hot && (
                <CustomTag color="volcano">
                  {typeof item.hot === 'number' ? item.hot.toLocaleString() : item.hot}
                </CustomTag>
              )}
            </div>
            {item.desc && (
              <motion.div 
                className="hot-item-description"
                style={{ color: theme.textSecondary }}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: index * 0.05 + 0.1 }}
              >
                {item.desc}
              </motion.div>
            )}
          </div>
          
          {item.pic && (
            <motion.img 
              src={item.pic} 
              alt={item.title}
              className="hot-item-image"
              style={{ 
                border: `1px solid ${theme.borderColor}`
              }}
              onError={(e) => {
                (e.target as HTMLImageElement).style.display = 'none';
              }}
              whileHover={{ 
                scale: 1.1,
                boxShadow: `0 8px 16px ${theme.glowColor}40`
              }}
              transition={{ duration: 0.3 }}
            />
          )}
        </motion.div>
      )
    }));
  };

  // 生成词云数据
  const generateWordCloudData = (data: HotItem[]) => {
    // 简单的词频统计示例
    const wordCount: Record<string, number> = {};
    
    data.forEach(item => {
      // 简单分词，实际应用中可以使用更复杂的分词库
      const words = item.title.split(/[\s\-_,.!?;:]/);
      words.forEach(word => {
        if (word.length > 1) { // 过滤掉单字符
          wordCount[word] = (wordCount[word] || 0) + 1;
        }
      });
    });
    
    // 转换为词云数据格式
    return Object.entries(wordCount)
      .map(([word, count]) => ({
        word,
        value: count * 10 // 放大数值以便更好地显示
      }))
      .sort((a, b) => b.value - a.value)
      .slice(0, 30); // 只取前30个词
  };

  // 生成饼图数据（按热度分组）
  const generatePieData = (data: HotItem[]) => {
    const hotCount = data.filter(item => item.hot && typeof item.hot === 'number' && item.hot > 1000000).length;
    const mediumCount = data.filter(item => item.hot && typeof item.hot === 'number' && item.hot > 100000 && item.hot <= 1000000).length;
    const lowCount = data.filter(item => !item.hot || (typeof item.hot === 'number' && item.hot <= 100000)).length;
    
    return [
      { type: '高热度', value: hotCount, color: '#ff4d4f' },
      { type: '中热度', value: mediumCount, color: '#faad14' },
      { type: '低热度', value: lowCount, color: '#52c41a' }
    ];
  };

  // 生成柱状图数据（按时间分布）
  const generateColumnData = (data: HotItem[]) => {
    // 简化的时间分布，实际应用中可以根据timestamp进行更精确的分组
    return [
      { category: 'Top 10', value: data.slice(0, 10).reduce((sum, item) => sum + (typeof item.hot === 'number' ? item.hot : 0), 0), color: '#1890ff' },
      { category: 'Top 20', value: data.slice(10, 20).reduce((sum, item) => sum + (typeof item.hot === 'number' ? item.hot : 0), 0), color: '#52c41a' },
      { category: '其余', value: data.slice(20).reduce((sum, item) => sum + (typeof item.hot === 'number' ? item.hot : 0), 0), color: '#722ed1' }
    ];
  };

  const currentData = hotData[selectedPlatform];
  
  const platformOptions = platforms?.platforms
    .filter(platform => platform.available)
    .map((platform: Platform) => ({
      value: platform.name,
      label: platform.platform_name,
    })) || [];

  return (
    <motion.div 
      className="hot-page-container"
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.5 }}
      style={{ 
        padding: '24px', 
        minHeight: '100vh', 
        backgroundColor: theme.contentBackground,
        color: theme.textPrimary
      }}
    >
      <motion.div
        initial={{ y: -20, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        transition={{ duration: 0.5 }}
      >
        <CustomCard>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <motion.h2 
              style={{ 
                margin: 0, 
                display: 'flex', 
                alignItems: 'center',
                color: theme.textPrimary,
                fontSize: '24px',
                fontWeight: 600
              }}
              initial={{ x: -20 }}
              animate={{ x: 0 }}
              transition={{ duration: 0.5 }}
            >
              <motion.span 
                style={{ color: '#ff4d4f', marginRight: 8, fontSize: '28px' }}
              >
                🔥
              </motion.span>
              实时热点数据
            </motion.h2>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <CustomSelect
                value={selectedPlatform}
                onChange={handlePlatformChange}
                options={platformOptions}
                loading={platformsLoading}
                placeholder="选择平台"
              />
              <CustomButton 
                type="primary"
                onClick={handleRefresh}
                loading={refreshLoading}
                icon={<>↻</>}
              >
                刷新数据
              </CustomButton>
            </div>
          </div>
          
          {currentData && (
            <motion.div 
              style={{ marginBottom: 16, color: theme.textSecondary }}
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.3 }}
            >
              {currentData.subtitle} • 更新时间: {new Date(currentData.update_time).toLocaleString()}
            </motion.div>
          )}
        </CustomCard>
      </motion.div>

      <motion.div
        initial={{ y: 20, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        transition={{ duration: 0.5, delay: 0.2 }}
        style={{ marginTop: '24px' }}
      >
        <AnimatePresence>
          {platformsError ? (
            <CustomAlert
              message="获取平台列表失败"
              description={platformsError}
              type="error"
              action={
                <CustomButton 
                  type="danger"
                  onClick={() => fetchPlatforms()}
                >
                  重试
                </CustomButton>
              }
            />
          ) : dataError ? (
            <CustomAlert
              message="获取数据失败"
              description={dataError}
              type="error"
              action={
                <CustomButton 
                  type="danger"
                  onClick={() => loadPlatformData(selectedPlatform)}
                >
                  重试
                </CustomButton>
              }
            />
          ) : refreshError ? (
            <CustomAlert
              message="刷新数据失败"
              description={refreshError}
              type="error"
              action={
                <CustomButton 
                  type="danger"
                  onClick={handleRefresh}
                >
                  重试
                </CustomButton>
              }
            />
          ) : isLoading || dataLoading ? (
            <CustomCard>
              <div className="hot-loading-container">
                <CustomSpin size="large" />
                <motion.div 
                  className="hot-loading-text"
                  style={{ color: theme.textPrimary }}
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  transition={{ duration: 0.5 }}
                >
                  正在加载热点数据...
                </motion.div>
              </div>
            </CustomCard>
          ) : currentData ? (
            <Row gutter={[24, 24]}>
              {/* 左侧：新闻列表 */}
              <Col xs={24} lg={12}>
                <CustomCard 
                  style={{
                    background: theme.cardBackground,
                    backdropFilter: mode === 'dark' ? 'blur(25px)' : 'blur(15px)',
                    border: `1px solid ${theme.cardBorder}`
                  }}
                >
                  <div className="hot-data-list-container">
                    <AnimatedList
                      items={convertToAnimatedListItems(currentData.data)}
                      maxHeight={600}
                      showGradients={true}
                      containerWidth="100%"
                      className="hot-data-list"
                    />
                  </div>
                </CustomCard>
              </Col>
              
              {/* 右侧：统计数据和词云 */}
              <Col xs={24} lg={12}>
                <Row gutter={[24, 24]}>
                  {/* 词云组件 */}
                  <Col span={24}>
                    <CustomWordCloud 
                      data={generateWordCloudData(currentData.data)}
                      title="热点词汇云"
                      height={300}
                    />
                  </Col>
                  
                  {/* 饼图组件 */}
                  <Col span={24}>
                    <CustomPieChart 
                      data={generatePieData(currentData.data)}
                      title="热度分布"
                      height={300}
                    />
                  </Col>
                  
                  {/* 柱状图组件 */}
                  <Col span={24}>
                    <CustomColumnChart 
                      data={generateColumnData(currentData.data)}
                      title="排名分布"
                      height={300}
                    />
                  </Col>
                </Row>
              </Col>
            </Row>
          ) : (
            <CustomCard>
              <div 
                className="hot-empty-state"
                style={{ color: theme.textSecondary }}
              >
                请选择一个平台查看热点数据
              </div>
            </CustomCard>
          )}
        </AnimatePresence>
      </motion.div>
    </motion.div>
  );
};

export default HotDataPage;